from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager

from tinystack.settings import *

Base = declarative_base()
engine = create_engine(DATABASE_URL)


@contextmanager
def session():
    Session = sessionmaker(bind=engine)
    try:
        session = Session()
        yield session
        session.commit()
    except:
        session.rollback()
    finally:
        session.close()


class Image(Base):
    __tablename__ = "image"

    id = Column(Integer, primary_key=True)
    uuid = Column(String(48))
    checksum = Column(String(48))
    name = Column(String(48))
    status = Column(String(48))

    def todict(self):
        return {
            "id": self.id,
            "uuid": self.uuid,
            "checksum": self.checksum,
            "name": self.name,
            "status": self.status
        }


class Flavor(Base):
    __tablename__ = "flavor"

    id = Column(Integer, primary_key=True)
    uuid = Column(String(48))
    name = Column(String(48))
    vcpu = Column(Integer)
    memory = Column(Integer)
    root = Column(Integer)

    # activate deleted
    status = Column(String(48))

    def todict(self):
        return {
            "id": self.id,
            "uuid": self.uuid,
            "name": self.name,
            "vcpu": self.vcpu,
            "memory": self.memory,
            "root": self.root
        }
